<template>
  <div class="update-photo" style="height:100%">
    <img class="img" :src="url" ref="image">
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>
           
<script>
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

import  {profile_api} from  '@/api/profile.js'
export default {
  props: ['url'],
  data() {
    return {
      myCropper: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    /* 
      进入组件需要做2步
      1、显示图片
      2、显示裁切效果
        1、下载一个包 cropperjs
        2、导入这个包文件和css文件
        3、需要初始化这个包文件   new出他的实例对象【实例对象中需要传入你要被裁切的img对象】
      */

    init() {
      this.myCropper = new Cropper(this.$refs.image, {
        viewMode: 1,
        dragMode: 'none',
        initialAspectRatio: 1,
        aspectRatio: 1,
        preview: '.before',
        background: false,
        autoCropArea: 0.6,
        zoomOnWheel: false
      })
    },
    onConfirm() {
      //点击裁切后的确认按钮
      /* 
      1、需要获取被裁切的图片资源====formData
      2、调用插件中的方法 来发送请求
      3、关闭对话框
      */

      this.myCropper.getCroppedCanvas().toBlob(
        async blob => {
          const formData = new FormData()
          // Pass the image file name as the third parameter if necessary.
          formData.append('photo', blob /*, 'example.png' */)
         //  发送请求
         const {data:res}=await profile_api(formData)
         console.log(res,4455);
         this.$emit('close')
        } /*, 'image/png' */
      )
    }
  }
}
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>